package com.fun.fun.profile;

import com.fun.frame.SourceCode;
import com.fun.profile.Constant;
import com.fun.utils.Regex;
import com.fun.utils.Time;

import java.io.File;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Properties;

/**
 * 存放一些系统初始化的方法，可被外部调用
 */
public class SysInit extends SourceCode {

    /**
     * 创建日志文件夹和数据存储文件夹
     */
    static {
        new File(Constant.LOG_Path).mkdir();
        new File(Constant.LONG_Path).mkdir();
        System.setProperty("logs", LOG_Path);
    }

    /**
     * 获取本机IP
     *
     * @return
     */
    public static String getLocalIp() {
        InetAddress inetAddress = null;
        try {
            inetAddress = inetAddress.getLocalHost();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        String ip = inetAddress.getHostAddress();
        return ip;
    }

    /**
     * 删除N小时以上的日志
     */
    @Deprecated
    public static void clearLog() {
        int hour = changeStringToInt(Time.getHour());
        File file = new File(Constant.LOG_Path);
        if (file.isDirectory()) {
            File[] list = file.listFiles();
            int length = list.length;
            if (length < 5) return;
            for (int i = 0; i < length; i++) {
                File ff = list[i];
                String name = ff.getName().replace(Constant.FILE_TYPE_LOG, Constant.EMPTY).replaceAll("[a-zA-Z]+", EMPTY);
                if (name.length() < 10 || !isNumber(name)) continue;
                int time = changeStringToInt(name.substring(0, 10));
                if (hour - time > 30) ff.delete();
            }
        }
    }

    /**
     * 获取本机用户username
     *
     * @return
     */
    public static String getComputerName() {
        Properties properties = System.getProperties();
        Object name = properties.get("user.name");
        return name.toString();
    }

    /**
     * 是否是黑名单的host
     *
     * @param name
     * @return
     */
    public static boolean isBlack(String name) {
        if (name.contains("10.10.32.155")) return true;
        name = Regex.regexAll(name, "\\..+?\\.").get(0).replaceAll("\\.", EMPTY);
        return Constant.BLACK_HOST.contains(name);
    }

}
